import 'package:gold/base/list_view_model.dart';
import 'package:gold/http/api_address.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/address_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/widgets/dialog/confirm_dialog.dart';

/// @description: 地址列表状态
/// @author tangzhentao
/// @created at 21:27 2024/12/7


class AddressViewmodel extends ListViewModel<AddressModel> {
  AddressViewmodel(super.api);

  /// 新增地址
  Future newAddress({AddressModel? address}) async {
    final result = await XfgNav.pushNamed<bool>(Routes.myAddressNew, arguments: address);
    if (result == true) {
      firstLoad();
    }
  }

  /// 修改默认地址
  Future changeDefault(int index) async {
    final item = list[index];
    final isDefault = item.isDefault == 1;
    final result = await Http().request<int>(ApiAddress.edit,
        data:  {'id': item.id,'name': item.name,'phone':item.phone,'address':item.address,'house_number':item.houseNumber,'is_default':isDefault ? 0:1,'sex':item.sex},
        loadingText: '加载中...'
    );
    if (result.success) {
      for (var address in list) {
        final sIndex = list.indexOf(address);
        if (sIndex == index) {
          address.isDefault = isDefault ? 0:1;
        } else {
         if (address.isDefault == 1 && !isDefault) {
           address.isDefault = 0;
         }
        }
      }
      setSuccessChange();
    }
  }

  /// 编辑地址
  Future modify(int index) async {
    final result = await XfgNav.pushNamed<bool>(Routes.myAddressNew, arguments: list[index]);
    if (result == true) {
      firstLoad();
    }
  }

  /// 删除地址
  Future delete(int index) async {
    final item = list[index];
    final dialog = await showConfirmDialog(title: '删除地址', content: '确认要删除地址：${item.address}${item.houseNumber}', cancel: '取消');
    if (dialog == true) {
      final result = await Http().request<int>(ApiAddress.delete, loadingText: '加载中...',
          data:  {'id': item.id});
      if (result.success) {
        list.removeAt(index);
        setSuccessChange();
      }
    }
  }
}